package com.ruoyi.system.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.result.Result;
import com.ruoyi.system.domain.Oss;
import com.ruoyi.system.mapper.OssMapper;
import com.ruoyi.system.service.IOssService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * <p>
 * 资源表 服务实现类
 * </p>
 *
 * @author FSD
 * @since 2024-02-18
 */
@Service("OssServiceImpl")
public class OssServiceImpl extends ServiceImpl<OssMapper, Oss> implements IOssService {
    @Resource
    OssMapper ossMapper;

    /**
     * 上传图片的实现类
     *
     * @param file
     * @return
     * @throws IOException
     */
    @Override
    public Result<String> upload(MultipartFile file) throws IOException {
        OSSClient ossClient = null;
        String objectName = null;
        try {
            String endpoint = "http://oss-cn-beijing.aliyuncs.com";
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = "LTAI5tGTEq7xnkNh4mruvrz8";
            String accessKeySecret = "JA3aPgqzznXCUVS0VicMVAe08FlQjp";
            // 创建OSSClient实例。
            ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
            // 上传内容到指定的存储空间（bucketName）并保存为指定的文件名称（objectName）。
            //content 上传文件内容
            String bucketName = "hgxd-02";
            objectName = UUID.randomUUID().toString().replaceAll("-", "").concat(".jpg");
            InputStream inputStream = file.getInputStream();
            System.out.println("file" + file);
//        ossClient.putObject(bucketName, objectName, inputStream);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            ossClient.shutdown();
            return Result.ok("https://hgxd-02.oss-cn-beijing.aliyuncs.com" + "/" + objectName);
        } catch (Exception oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return Result.ok("https://hgxd-02.oss-cn-beijing.aliyuncs.com" + "/" + objectName);
    }


    /**
     * 下载图片的实现类
     *
     * @param request
     * @param response
     * @param urlString
     * @return
     * @throws IOException
     */

    @Override
    public Result<String> download(HttpServletRequest request, HttpServletResponse response, String urlString) throws IOException {
        String endpoint = "http://oss-cn-beijing.aliyuncs.com";
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAI5tGTEq7xnkNh4mruvrz8";
        String accessKeySecret = "JA3aPgqzznXCUVS0VicMVAe08FlQjp";
        String bucketName = "hgxd-02";
        String objectName = urlString;
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(objectName.getBytes("utf-8"), "ISO8859-1"));
        // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>oss下载<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        String key = objectName.toString();
        key = key.replaceAll("\\\\", "/");
        OSSObject object = ossClient.getObject(bucketName, key);
        BufferedInputStream input = new BufferedInputStream(object.getObjectContent());
        byte[] buffBytes = new byte[1024];

        OutputStream outputStream = response.getOutputStream();

        int read = 0;
        while ((read = input.read(buffBytes)) != -1) {
            outputStream.write(buffBytes, 0, read);
        }

        outputStream.flush();
        outputStream.close();
        //is.close();
        input.close();
        ossClient.shutdown();
        return null;
    }

}
